import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lottie/lottie.dart';
import 'package:video_player/video_player.dart';

import '../../entity/xmm_video_info.dart';

class XmmVideoWidget extends StatefulWidget {
  const XmmVideoWidget(this.videoInfo, {super.key});

  final XmmVideoInfo videoInfo;

  @override
  XmmVideoWidgetState createState() => XmmVideoWidgetState();
}

class XmmVideoWidgetState extends State<XmmVideoWidget> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    var uri = Uri.parse(widget.videoInfo.mediaUrl ?? "");
    _controller = VideoPlayerController.networkUrl(uri);
    _controller.setLooping(false);
    _controller.addListener(() {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
    _controller.initialize().then((_) => setState(() {}));
    _controller.play();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: getVideoWidget(),
    );
  }

  Widget getVideoWidget() {
    if (_controller.value.isInitialized) {
      return AspectRatio(
        aspectRatio: _controller.value.aspectRatio,
        child: GestureDetector(
          child: Stack(
            alignment: Alignment.bottomCenter,
            children: [
              CachedNetworkImage(imageUrl: widget.videoInfo.middleThumbUrl ?? ""),
              VideoPlayer(_controller),
              Align(alignment: Alignment.center, child: getContentWidget()),
              VideoProgressIndicator(_controller, allowScrubbing: true)
            ],
          ),
          onTap: () {
            setState(() {
              if (_controller.value.isPlaying) {
                _controller.pause();
              } else {
                _controller.play();
              }
            });
          },
        ),
      );
    }
    return Container();
  }

  Widget getContentWidget() {
    if (_controller.value.isBuffering) {
      return const CircularProgressIndicator(color: Colors.white);
    } else if (!_controller.value.isPlaying) {
      return Icon(Icons.play_circle, size: 50.w, color: Colors.white);
    } else {
      return SizedBox(width: 50.w, height: 50.w);
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
